package cn.iocoder.yudao.module.biz.controller.admin.ticket;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.biz.controller.admin.ticket.vo.*;
import cn.iocoder.yudao.module.biz.convert.ticket.BizTicketConvert;
import cn.iocoder.yudao.module.biz.dal.dataobject.ticket.BizTicketDO;
import cn.iocoder.yudao.module.biz.service.ticket.BizTicketService;
import cn.iocoder.yudao.module.infra.dal.dataobject.oss.OssDO;
import cn.iocoder.yudao.module.infra.service.oss.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 票证管理")
@RestController
@RequestMapping("/biz/ticket")
@Validated
public class BizTicketController {

    @Resource
    private BizTicketService ticketService;
    @Resource
    private OssService ossService;

    @PostMapping("/create")
    @ApiOperation("创建票证管理")
    @PreAuthorize("@ss.hasPermission('biz:ticket:create')")
    public CommonResult<String> createTicket(@Valid @RequestBody BizTicketCreateReqVO createReqVO) {
        return success(ticketService.createTicket(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新票证管理")
    @PreAuthorize("@ss.hasPermission('biz:ticket:update')")
    public CommonResult<Boolean> updateTicket(@Valid @RequestBody BizTicketUpdateReqVO updateReqVO) {
        ticketService.updateTicket(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除票证管理")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('biz:ticket:delete')")
    public CommonResult<Boolean> deleteTicket(@RequestParam("id") String id) {
        ticketService.deleteTicket(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得票证管理")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('biz:ticket:query')")
    public CommonResult<BizTicketRespVO> getTicket(@RequestParam("id") String id) {
        BizTicketDO ticket = ticketService.getTicket(id);
        return success(BizTicketConvert.INSTANCE.convert(ticket));
    }

    @GetMapping("/list")
    @ApiOperation("获得票证管理列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('biz:ticket:query')")
    public CommonResult<List<BizTicketRespVO>> getTicketList(@RequestParam("ids") Collection<String> ids) {
        List<BizTicketDO> list = ticketService.getTicketList(ids);
        return success(BizTicketConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得票证管理分页")
    @PreAuthorize("@ss.hasPermission('biz:ticket:query')")
    public CommonResult<PageResult<BizTicketRespVO>> getTicketPage(@Valid BizTicketPageReqVO pageVO) {
        PageResult<BizTicketDO> pageResult = ticketService.getTicketPage(pageVO);
        List<BizTicketDO> list = pageResult.getList();
        if (list.isEmpty()) {
            return success(BizTicketConvert.INSTANCE.convertPage(pageResult));
        }
        Set<String> fileIds = list.stream().map(p -> p.getAppendix().toString()).collect(Collectors.toSet());
        List<OssDO> fileList = ossService.selectByIds(fileIds);
        Map<Long, List<OssDO>> map = fileList.stream().collect(Collectors.groupingBy(OssDO::getId));

        PageResult<BizTicketRespVO> pageResultConvert = BizTicketConvert.INSTANCE.convertPage(pageResult);
        pageResultConvert.getList().forEach(p -> {
            if (!ObjectUtils.isEmpty(p.getAppendix()) && map.containsKey(p.getAppendix())) {
                p.setFileName(map.get(p.getAppendix()).get(0).getOriginalName());
            } else {
                p.setFileName(StringUtils.EMPTY);
            }
        });

        return success(pageResultConvert);
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出票证管理 Excel")
    @PreAuthorize("@ss.hasPermission('biz:ticket:export')")
    @OperateLog(type = EXPORT)
    public void exportTicketExcel(@Valid BizTicketExportReqVO exportReqVO,
                                  HttpServletResponse response) throws IOException {
        List<BizTicketDO> list = ticketService.getTicketList(exportReqVO);
        // 导出 Excel
        List<BizTicketExcelVO> datas = BizTicketConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "票证管理.xls", "数据", BizTicketExcelVO.class, datas);
    }

}
